<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Apply extends Base {
	private $application;

	// construct
	public function run() {
		// get applications category id
		$this->application = $this->db->querySingle("SELECT id FROM categories WHERE type = 2 ORDER BY position ASC");
		if(is_null($this->application))
			die(new Error());

		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func) = $this->uri;
			$this->$func();
		} else $this->index();
	}

	// default action
	public function index() {
		// not logged in?
		$this->view->func = 'index';

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);

		// not logged in? abort
		if(!isset($this->session->auth))
			return;

		// already made an application ?
		$result = $this->db->querySingle("SELECT id, name FROM topics WHERE author = '{$this->session->auth['id']}' AND category = {$this->application}", true);
		if($result) {
			$link = $result['id'] . '-' . Helper::generate_named_id($result['name']);
			die(new Forum(array('topic', $link)));
		}
	}

	// apply without account
	public function submit() {
		// get from post
		$email = $this->request->post('email');
		$password = $this->request->post('password');
		$name = $this->request->post('name');
		$class = $this->request->post('class');
		$armory_url = $this->request->post('armory_url');
		$real_name = $this->request->post('real_name');
		$country = $this->request->post('country');
		$age = $this->request->post('age', 'int');
		$microphone = $this->request->post('microphone');
		$experience = $this->request->post('experience');
		$reason = $this->request->post('reason');
		if(is_null($email) || is_null($password) || is_null($name) || is_null($class) || is_null($armory_url) || is_null($real_name) || is_null($country) || is_null($age) || is_null($microphone) || is_null($experience) || is_null($reason))
			return $this->json = array('success' => false);

		// use this cookie file
		$jar = $this->jar();

		// register user
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, URL ."login/signup");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, array(
		    'name' => $name,
		    'email' => $email,
		    'password' => $password,
		));
		curl_setopt($ch, CURLOPT_COOKIEFILE, $jar);
		curl_setopt($ch, CURLOPT_COOKIEJAR, $jar);
		$login_output = curl_exec($ch);
		curl_close($ch);

		// post topic
		$post_output = $this->post($class, $armory_url, $real_name, $country, $age, $microphone, $experience, $reason, $jar);

		// read the cookie jar
		$login = null;
		foreach(file($jar) as $line) {
			if($line[0] != '#' && substr_count($line, "\t") == 6) {
				$tokens = explode("\t", $line);
				$tokens = array_map('trim', $tokens);
			}

			if(isset($tokens) && $tokens[5] == 'auth' && $tokens[6])
				$login = $tokens[6];
		}

		// login based on cookie gathered
		if(!is_null($login))
			$this->cookie->auth = rawurldecode($login);

		// remove cookie jar
		unlink($jar);

		// build data
		$data = array_merge(json_decode($login_output, true), json_decode($post_output, true));

		// notify staff
		$this->staff($data);

		// yay success
		return $this->json = $data;
	}

	// apply with account
	public function acknowledge() {
		// get from post
		$class = $this->request->post('class');
		$armory_url = $this->request->post('armory_url');
		$real_name = $this->request->post('real_name');
		$country = $this->request->post('country');
		$age = $this->request->post('age', 'int');
		$microphone = $this->request->post('microphone');
		$experience = $this->request->post('experience');
		$reason = $this->request->post('reason');
		if(is_null($class) || is_null($armory_url) || is_null($real_name) || is_null($country) || is_null($age) || is_null($microphone) || is_null($experience) || is_null($reason))
			return $this->json = array('success' => false);

		// post topic
		$post_output = $this->post($class, $armory_url, $real_name, $country, $age, $microphone, $experience, $reason);

		// build data
		$data = json_decode($post_output, true);

		// notify staff
		$this->staff($data);

		// yay success
		return $this->json = $data;
	}

	// create the cookie jar
	private function jar() {
		$jar = ROOT . DS . 'tmp' . DS . uniqid('cookie_jar'). '.txt';
		if(!file_exists($jar)) {
		    $fh = fopen($jar, "w");
		    fwrite($fh, "");
		    fclose($fh);
		}

		return $jar;
	}

	// post topic
	private function post($class, $armory_url, $real_name, $country, $age, $microphone, $experience, $reason, $jar = false) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, URL ."forum/create");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, array(
		    'id' => $this->application,
		    'title' => $class,
		    'message' =>
		    	'[b]Armory[/b][/br]'.
		    	$armory_url .'[/br][/br]'.
		    	'[b]Real Name[/b][/br]'.
		    	$real_name .'[/br][/br]'.
		    	'[b]Country[/b][/br]'.
		    	$country .'[/br][/br]'.
		    	'[b]Age[/b][/br]'.
		    	$age .'[/br][/br]'.
		    	'[b]Microphone[/b][/br]'.
		    	$microphone .'[/br][/br]'.
		    	'[b]Experience[/b][/br]'.
		    	$experience .'[/br][/br]'.
		    	'[b]Argumentation[/b][/br]'.
		    	$reason,
		    'permission' => '1' // possible entry point
		));

		// use the cookie jar or send the session
		if($jar) curl_setopt($ch, CURLOPT_COOKIEFILE, $jar);
		else {
    		curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id() . '; path=/');
    		session_write_close();
		}

		// exec curl
		$post_output = curl_exec($ch);
		curl_close($ch);

		// return shit
		return $post_output;
	}

	// notify staff
	private function staff($data) {
		// get all users with their permissions
		$result = $this->db->query("SELECT u.name, u.email, r.permissions FROM users AS u LEFT JOIN ranks AS r ON u.rank = r.id");

		// send a nice email to staff
		while($res = $result->fetchArray(SQLITE3_ASSOC)) {
			// no permission found? odd
			if(!$res['permissions'])
				continue;

			// no permission to moderate the application category? continue to next user
			$permissions = unserialize($res['permissions']);
			if(!isset($permissions['forum']['moderate'][$this->application]))
				continue;

			// send the email
			$eml = Helper::load_email('application.txt', $res['name'], $data['name'], $this->settings['blizz_guild'], URL . 'forum/topic/' . $data['link'], $this->settings['blizz_guild']);
			if($eml)
				$this->email->send($res['email'], $res['name'], $eml);
		}
	}
}